import { ImagePreview } from 'vant'
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'
import { tokenManage } from 'utils/Cache'
import { getUserInfo } from 'api/account'
const fightSkuMixin = {
    data() {
        return {
            goodsNum: 1, //sku购买数量
            skuList: '', //sku集合
            stocks: 0, //库存
            skuImages: '', //sku的图片
            promotionPrice: 0,
            paramData: null,
            prodName: '',
            skuBanner: '', //sku图片的集合
            picPreview: '', //图片预览
            shareConfig: {},
            posterShow: false,
            posterDataUrl: '',

            shareUrl: window.location.href,

            isLogin: tokenManage.getToken() ? true : false, //默认没登录

            //头像跟名字
            posterAttr: {
                name: '',
                pic: ''
            }
        }
    },
    methods: {
        buildSkuList() {
            const propObjs = this.propObjs
            // 用前面的拼最后一个
            this.skuList = propObjs.reduce((res, propObj) => {
                propObj.properties.forEach((p, i) => {
                    let _ids = p.split(':')
                    let _values = propObj.cnProperties[i].split(':')
                    let prop = res.find((v) => v && _ids[0] == v.id)
                    if (prop) {
                        let idx = prop.propValues.findIndex((pv) => {
                            return pv && pv.id === _ids[1]
                        })
                        if (idx == -1) {
                            prop.propValues.push({
                                id: _ids[1],
                                propValue: _values[1]
                            })
                        }
                    } else {
                        res.push({
                            id: _ids[0],
                            propName: _values[0],
                            propValues: [
                                {
                                    id: _ids[1],
                                    propValue: _values[1]
                                }
                            ]
                        })
                    }
                })
                return res
            }, [])
            this.initSkuList()
        },

        getKey(fid, sid) {
            let _d = {
                ...this.cuccentValue
            }
            _d[fid] = sid
            return this.skuList
                .reduce((res, cur) => {
                    res.push(`${cur.id}:${_d[cur.id]}`)
                    return res
                }, [])
                .join(';')
        },
        //初始化
        initSkuList() {
            let cuccentValue = this.cuccentValue
            let skuList = [...this.skuList.map((v) => v)]
            skuList.forEach((f) => {
                f.propValues.forEach((s) => {
                    let key = this.getKey(f.id, s.id)
                    let sku = this.map[key]
                    s.isEnable = sku && (sku.status != 1 || sku.stocks <= 0) ? false : true
                    s.isSelect = s.isEnable && cuccentValue[f.id] === s.id
                    s.key = key
                    s.sku = sku
                })
            })
            this.skuList = skuList
        },

        closeCode() {
            this.posterShow = false
        },
        //选择sku的图片预览
        imageSkuPreview(pic) {
            if (!this.skuImages) {
                return
            }

            let arrPic = []
            arrPic.push(pic)
            this.picPreview = ImagePreview({
                images: arrPic,
                onClose() {
                    // do something
                }
            })
        },

        //选择sku
        currentFilter(pid, vid, key) {
            let cuccentValue = {
                ...this.cuccentValue
            }

            cuccentValue[pid] = vid

            this.cuccentValue = cuccentValue

            this.initSkuList()

            this.currentSku = this.map[key]

            // 商品起售限制
            if (this.fightDetail.startSale) {
                this.goodsNum = this.fightDetail.startSaleAmount
            } else {
                this.goodsNum = 1
            }

        },

        //减
        reduce() {
            // 起购判断
            if (this.fightDetail.startSale) {
                if (this.goodsNum <= this.fightDetail.startSaleAmount) {
                    this.$toast(`活动起售${this.fightDetail.startSaleAmount}件`)
                    return
                }
            }

            if (this.goodsNum <= 1) {
                return
            }
            this.goodsNum--
        },
        
        //加
        add() {
            // 限购判断
            if (this.fightDetail.purchaseLimitMode && this.fightDetail.purchaseLimitMode != 'NOT_LIMIT') {
								let limitMode = {'EVERY_ORDER':'每单','EVERY_DAY':'每天', 'EVERY_WEEK': '每周', 'EVERY_MONTH':'每月', 'EVERY_YEAR': '每年', 'FOREVER':'终身'}[this.fightDetail.purchaseLimitMode]
                if (this.goodsNum >= (this.fightDetail.purchaseLimitAmount - (this.currentSku.intervalOrderCount || 0))) {
                    this.$toast(`该活动${limitMode}限购${this.fightDetail.purchaseLimitAmount}件,您已下单${this.currentSku.intervalOrderCount > 0 ? this.currentSku.intervalOrderCount:'0'}件`)
                    return
                }
            }

            if (this.goodsNum == this.currentSku.stocks) {
                return
            } else {
                if (this.currentSku.stocks == 0) {
                    return
                }
            }
            if (this.fightDetail.isLimit == false) {
                if (this.goodsNum + 1 > this.currentSku.stocks) {
                    this.$toast({
                        message: `此商品最大购买数量为${this.currentSku.stocks}`,
                        duration: 800
                    })
                    this.goodsNum = this.currentSku.stocks
                    return
                }
            } else {
                if (this.currentSku.stocks == 0) {
                    this.$toast('您好，你选择得此商品属性库存为0')
                    return
                }
                if (this.goodsNum + 1 > this.fightDetail.limitNumber - (this.currentSku.intervalOrderCount || 0)) {
                    this.$toast({
                        message: `该拼团活动限购${this.fightDetail.limitNumber}件，已购${this.currentSku.intervalOrderCount}件`,
                        duration: 800
                    })
                    return
                }
            }
			this.goodsNum++
        },

        // 手动修改商品数量
        changeGoodsNum() {
            if (this.goodsNum > this.currentSku.stocks) {
                this.goodsNum = this.currentSku.stocks
                this.$toast({
                    message: `此商品最大购买数量为${this.currentSku.stocks}`,
                    duration: 800
                })
            }

            if (this.fightDetail.isLimit) {
                if (this.goodsNum >= this.fightDetail.limitNumber) {
                    this.$toast({
                        message: `该拼团活动限购${this.fightDetail.limitNumber}件`,
                        duration: 800
                    })
                    this.goodsNum = this.fightDetail.limitNumber
                    return
                }
            }
        },

        // 商品数量校验
        checkGoodsNum() {
            // 起售判断
            if (this.fightDetail.startSale && this.goodsNum < this.fightDetail.startSaleAmount) {
                this.$toast(`商品起购${this.fightDetail.startSaleAmount}件`)
                return
            }

            // 限购判断
            if (
                this.fightDetail.purchaseLimitMode &&
                this.fightDetail.purchaseLimitMode != 'NOT_LIMIT' &&
                this.goodsNum > this.fightDetail.purchaseLimitAmount
            ) {
                this.$toast(`商品限购${this.fightDetail.purchaseLimitAmount}件`)
                return
            }

            if (this.goodsNum <= 0) {
                this.goodsNum = 1
            }
        },

        // 分享
        share() {
            this.$refs.shareSheet.sheetShow = true

            this.shareConfig.name = this.fightDetail.name
            this.shareConfig.isPromoter = this.fightDetail.isPromoter
            this.shareConfig.supportDist = this.fightDetail.supportDist
            this.shareConfig.commission = this.fightDetail.commission

            if (!this.posterDataUrl) {
                if (this.isLogin) {
                    getUserInfo()
                        .then((res) => {
                            if (res.status == 1) {
                                this.posterAttr.name = res.result.nickName
                                this.posterAttr.pic = res.result.headPortrait
                            } else {
                                this.posterAttr.name = '匿名'
                                this.posterAttr.pic = ''
                            }
                        })
                        .catch(() => {
                            this.posterAttr.name = '匿名'
                            this.posterAttr.pic = ''
                        })
                } else {
                    this.posterAttr.name = '匿名'
                    this.posterAttr.pic = ''
                }
            }
        },

        async createQRCode() {
            // 配置项
            const options = {
                width: 80,
                height: 80,
                background: '#ffffff',
                colorDark: '#000000',
                margin: 1
            }

            const result = await QRCode.toDataURL(this.shareUrl, options)
            const images = document.createElement('img')
            images.setAttribute('src', result)
            this.$refs.qrcode.appendChild(images)

            // 手动创建一个 canvas 标签
            let canvas = document.createElement('canvas')
            // // 获取父标签，意思是这个标签内的 DOM 元素生成图片
            let canvasBox = this.$refs.poster

            // // 获取父级的宽高
            const width = parseInt(window.getComputedStyle(canvasBox).width)
            const height = parseInt(window.getComputedStyle(canvasBox).height)

            let rect = canvasBox.getBoundingClientRect() //获取元素相对于视察的偏移量

            // // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
            // canvas.width = width * 2
            // canvas.height = height * 2
            // canvas.style.width = width + 'px'
            // canvas.style.height = height + 'px'

            // const context = canvas.getContext("2d");
            // context.scale(2, 2);
            // context.translate(-rect.left,-rect.top);

            const options1 = {
                // backgroundColor: null,
                // canvas: canvas,
                width: width,
                height: height,
                allowTaint: false,
                dpi: window.devicePixelRatio * 2,
                scale: 2,
                useCORS: true
            }

            // setTimeout(() =>{
            html2canvas(canvasBox, options1).then((canvas) => {
                // toDataURL 图片格式转成 base64
                let dataURL = canvas.toDataURL('image/png', 1.0)

                this.posterDataUrl = dataURL
            })
            // },300)
        }
    }
}

export default fightSkuMixin
